package com.seele.tigerwallet.ui.activtiy;

import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.TokenInfoModel;
import com.seele.tigerwallet.model.WalletFlagModel;
import com.seele.tigerwallet.model.WalletInfoModel;
import com.seele.tigerwallet.ui.RegisterActivity;
import com.seele.tigerwallet.ui.adapter.ManageWalletAdapter;
import com.seele.tigerwallet.ui.base.TitleBaseActivity;
import com.seele.tigerwallet.ui.event.MessageEvent;
import com.seele.tigerwallet.ui.event.WalletEvent;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.utils.GsonUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.utils.TypefaceUtils;
import com.seele.tigerwallet.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.List;

import retrofit2.Call;

/**
 * Description:钱包管理界面
 * Data: 2018/6/11 19:55
 * author: 郑波
 */
public class ManageWalletActivity extends TitleBaseActivity implements View.OnClickListener {


    private RecyclerView mRecyclerView;
    private ManageWalletAdapter mManageWalletAdapter;
    private WalletAsyncTask mWalletAsyncTask;
    private ImageView mCompanyImg;

    private TextView mtitleTv;

    private TextView mAssetsTv;

    private TextView mCreateWalletTv;


    private TextView mImportWalletTv;
    private int mAllAssets;
    private List<TokenInfoModel> mTokenInfoModels;


    @Override
    public int getContainerViewId() {
        return R.layout.activity_manage_wallet;
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        setTitle(R.string.manage_wallet);
        mRecyclerView = $f(R.id.manage_wallet_recyclerView);
        mCompanyImg = $f(R.id.company_img);
        if (SPUtils.isCNY()) {
            mCompanyImg.setImageDrawable(getResources().getDrawable(R.drawable.company_icon));
        } else {
            mCompanyImg.setImageDrawable(getResources().getDrawable(R.drawable.usd));
        }
        mManageWalletAdapter = new ManageWalletAdapter(R.layout.item_wallet_manage);
        mtitleTv = $f(R.id.wallet_title_tv);
        mAssetsTv = $f(R.id.all_assets_tv);
        mCreateWalletTv = $f(R.id.create_wallet_tv);
        mImportWalletTv = $f(R.id.import_wallet_tv);

        mCreateWalletTv.setOnClickListener(this);
        mImportWalletTv.setOnClickListener(this);
        TypefaceUtils.setCenturyGothicBold(mAssetsTv, ManageWalletActivity.this);

        if (null == mWalletAsyncTask) {
            mWalletAsyncTask = new WalletAsyncTask();
        }
        mWalletAsyncTask.execute();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mManageWalletAdapter);
        mManageWalletAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (isaBoolean()) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(ManageWalletInfoActivity.class.getSimpleName(), mTokenInfoModels.get(position));
                    startActivity(ManageWalletInfoActivity.class, bundle);
                }

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.create_wallet_tv:
                WalletFlagModel walletFlagModel = new WalletFlagModel();
                walletFlagModel.isCrate = true;
                walletFlagModel.flag = 50;
                Bundle bundle = new Bundle();
                bundle.putSerializable(RegisterActivity.class.getSimpleName(), walletFlagModel);
                startActivity(RegisterActivity.class, bundle);
                break;
            case R.id.import_wallet_tv:
                WalletFlagModel walletFlagModel2 = new WalletFlagModel();
                walletFlagModel2.isCrate = false;
                walletFlagModel2.flag = 50;
                Bundle bundle2 = new Bundle();
                bundle2.putSerializable(RegisterActivity.class.getSimpleName(), walletFlagModel2);
                startActivity(RegisterActivity.class, bundle2);
                break;
        }

    }


    class WalletAsyncTask extends AsyncTask<Void, Void, List<TokenInfoModel>> {


        public WalletAsyncTask() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<TokenInfoModel> doInBackground(Void... voids) {
            try {
                List<TokenInfoModel> tokenInfoModels = DaoManager.getTokenDao().queryForAll();
                //查询本地数据
//                for (TokenInfoModel tokenInfoModel : tokenInfoModels) {
//                    if (!TextUtils.isEmpty(tokenInfoModel.address)) {
//                        GenericRawResults<String[]> queryRaw = DaoManager.getAssetsDao().queryRaw(getSql(tokenInfoModel.address));
//                        String[] resultArray = queryRaw.getFirstResult();
//                        String total = resultArray[0];
//                        tokenInfoModel.total = total;
//                    }
//                }
                if (null != tokenInfoModels && tokenInfoModels.size() > 0) {


                    for (int i = 0; i < tokenInfoModels.size(); i++) {
                        if (!TextUtils.isEmpty(tokenInfoModels.get(i).address)) {
                            //根据条件查询本地的数据库
                            List<AssetsModel> assetsModelList = DaoManager.getAssetsDao().queryBuilder().where().eq("address", tokenInfoModels.get(i).address).query();
                            if (null != assetsModelList && assetsModelList.size() > 0) {
                                tokenInfoModels.get(i).assetsModelList = assetsModelList;
                            }
                        }
                        //如果钱包名字为空 添加名字
                        if (TextUtils.isEmpty(tokenInfoModels.get(i).name)) {
                            tokenInfoModels.get(i).name = getResources().getString(R.string.wallet_name + i);
                        }
                    }


                }


                if (null != tokenInfoModels) {
                    return tokenInfoModels;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }


        @Override
        protected void onPostExecute(List<TokenInfoModel> tokenInfoModels) {

            if (null != tokenInfoModels && tokenInfoModels.size() > 0) {
                mTokenInfoModels = tokenInfoModels;
                handlerData();
            }
            super.onPostExecute(tokenInfoModels);
        }


        @Override
        protected void onCancelled(List<TokenInfoModel> tokenInfoModels) {
            super.onCancelled(tokenInfoModels);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }


    int count = 0;


    /**
     * 请求网络资产
     *
     * @param
     */
    @NonNull
    private void handlerData() {

        mManageWalletAdapter.setNewData(mTokenInfoModels);
        mManageWalletAdapter.notifyDataSetChanged();


        for (final TokenInfoModel tokenInfoModel : mTokenInfoModels) {

            if (null != tokenInfoModel.assetsModelList && tokenInfoModel.assetsModelList.size() > 0 && !TextUtils.isEmpty(tokenInfoModel.address)) {
                StringBuilder stringBuilder = new StringBuilder();
                if (null == tokenInfoModel.assetsModelList || tokenInfoModel.assetsModelList.size() == 0) {
                    stringBuilder.append(Constants.ETH);
                } else {
                    for (int i = 0; i < tokenInfoModel.assetsModelList.size(); i++) {
                        stringBuilder.append(tokenInfoModel.assetsModelList.get(i).id);
                        if (i != tokenInfoModel.assetsModelList.size() - 1) {
                            stringBuilder.append(",");
                        }
                    }
                }

                if (null != stringBuilder) {
                    APIModule.
                            getApi().
                            querySymbol(tokenInfoModel.address, stringBuilder.toString()).
                            enqueue(new APIListCallBack<AssetsModel>() {
                                @Override
                                protected void onResponseError(APIException e) {
                                    count++;
                                    getAllAssets(mTokenInfoModels);

                                }

                                @Override
                                protected void onFailureError(Call<String> call, Throwable t) {
                                    count++;
                                    getAllAssets(mTokenInfoModels);
                                }

                                @Override
                                protected void onResponse(List<AssetsModel> response) {
                                    count++;
                                    float allTotal = 0;
                                    if (null != response && response.size() > 0) {
                                        for (AssetsModel assetsModel : response) {
//                                            float total = assetsModel.price * assetsModel.balance;
//                                            allTotal += total;
//                                            assetsModel.total = total+"";
                                        }
                                    }
                                    tokenInfoModel.total = allTotal;
                                    mManageWalletAdapter.setNewData(mTokenInfoModels);
                                    mManageWalletAdapter.notifyDataSetChanged();
                                    getAllAssets(mTokenInfoModels);
                                }
                            });
                }
            }
        }

    }

    private void getAllAssets(List<TokenInfoModel> tokenInfoModels) {
        if (count == tokenInfoModels.size()) {
            for (TokenInfoModel infoModel : tokenInfoModels) {
                mAllAssets += infoModel.total;
//                mAssetsTv.setText("≈ " + SPUtils.getTotal(mAllAssets));
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event instanceof WalletEvent) {
            try {
                WalletEvent walletEvent = (WalletEvent) event;
                if (null == walletEvent) {
                    return;
                }
                if (isaBoolean()) {
                    for (TokenInfoModel mTokenInfoModel : mTokenInfoModels) {
                        if (mTokenInfoModel.address.equals(walletEvent.address)) {
                            mTokenInfoModel.name = walletEvent.name;
                        }
                    }
                }

                mManageWalletAdapter.notifyDataSetChanged();
//                handlerData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    private boolean isaBoolean() {
        return null != mTokenInfoModels && mTokenInfoModels.size() > 0;
    }


    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    public String getSql(String address) {

        return String.format(" SELECT  sum(total)  FROM t_assets  where address='%s'", address);
    }
}
